<?php
declare (strict_types=1);
namespace app\common\model;
use think\Model;
/**
* 三级地区
*/
class Region extends Model
{
	// 定义表名
    protected $name = 'region';

    // 定义主键
    protected $pk = 'id';

    // 追加字段
    // protected $append = [''];
    
    /**
     * [获取地区树]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function tree()
    {
    	$hidden = [];
    	$all = $this->select()->toArray();
        $province = [];
        $city = [];
        $region = [];
        foreach ($all as $key => $val) {
            if ($val['level'] == 1) {
                array_push($province, $val);
            }
            if ($val['level'] == 2) {
                array_push($city, $val);
            }
            if ($val['level'] == 3) {
                array_push($region, $val);
            }
        }
        foreach ($city as $k => $v) {
            foreach ($region as $key => $val) {
                if ($v['id'] == $val['pid']) {
                    $city[$k]['children'][] = $val;
                }
            }
        }
        foreach ($province as $k => $v) {
            foreach ($city as $key => $val) {
                if ($v['id'] == $val['pid']) {
                    $province[$k]['children'][] = $val;
                }
            }
        }
    	return $province;
    }
    /**
     * [children 生成地区树]
     * Author：上官钧墨
     * @param  array  $all [所有数据]
     * @param  integer $pid [上级menu_id]
     */
    private function childrens($all,$pid = 0){
        $list = [];
        foreach ($all as $v) {
            if ($v['pid'] == $pid) {
                $item = $this->childrens($all,$v['pid']);
                !empty($item) && $v['children'] = $item;
                $list[] = $v;
                unset($item);
            }
        }
        return $list;
    }
}